$(() => {
    const $searchBar = $('#searchBar');
    const $searchBtn = $('#searchBtn');
    const $filterBtn = $('#filterBtn');
    const $appointmentsList = $('#appointmentsList');


    // 尝试从localStorage获取用户信息
    let loginUser = localStorage.getItem('userInfo');
    if (loginUser) {
        loginUser = JSON.parse(loginUser);
    }
    let appointments;
    let patId = loginUser.patId;
    fetchAppointments();

    // 定义一个函数来处理 AJAX 请求
    function fetchAppointments(date) {
        $.ajax({
            url: ctx + "/client/appoint",
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({
                patId: patId,
                date: date
            }),
            success: function (resp) {
                appointments = resp.data;
                // 数据成功获取时执行的函数
                displayAppointments(resp.data);
            },
            error: function (xhr, status, error) {
                // 数据获取失败时执行的函数
                console.error('Error:', error);
            }
        });
    }

    /**
     * 数据展示区域
     * @param appointments
     */
    function displayAppointments(appointments) {
        $appointmentsList.empty(); // 清空列表
        appointments.forEach(appointment => {
            const appointmentElem = $('<div>', {
                class: 'appointment'
            }).append(
                $('<p>').text(`患者姓名：${appointment.patName}`),
                $('<p>').text(`医生姓名：${appointment.docName}`),
                $('<p>').text(`叫号状态：${appointment.status}`),
                $('<p>').text(`预约时间：${appointment.appointTime}`),
                $('<p>').text(`预约费用：${appointment.money}`),
                $('<p>').text(`病例详情：${appointment.remark || '目前暂无病例'}`).appendTo('#appointmentsList')
            );
            // 如果预约状态为“待叫号”，则添加取消预约按钮
            if (appointment.status === '待叫号') {
                const cancelBtn = $('<button>', {
                    type: 'button',
                    text: '取消预约',
                    class: 'cancel-appointment-btn',
                    click: function () {
                        // 取消预约的逻辑
                        fetchCancelAppointment(appointment);
                        console.log('取消预约：', appointment);

                    }
                });
                appointmentElem.append(cancelBtn);
            }
            $appointmentsList.append(appointmentElem);
        });
    }

    // 搜索按钮点击事件
    $searchBtn.click(function () {
        const selectedTimeRange = $('#timeRange').val(); // 从时间范围选择框获取选中的值
        if (selectedTimeRange) {
            console.log('Selected Time Range:', selectedTimeRange);
            fetchAppointments(selectedTimeRange); // 执行时间范围查询
        } else {
            console.error('请选择时间范围');
        }
    });


// 点击取消按钮执行操作业务
    function fetchCancelAppointment(appoint) {
        $.ajax({
            url: ctx + "/client/cancelAppoint", // 替换为您的 API 路径
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(appoint),
            success: function (resp) {
                // 取消预约成功时的逻辑
                alert('取消预约成功！');
            },
            error: function (xhr, status, error) {
                // 取消预约失败时的逻辑
                alert(error);
            }
        });
        fetchAppointments();
    }
});
